﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace rsdeploygui
{
    // Found this class here
    // http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/9ced73d3-8f59-4a00-b174-e469410c735f

    public class TextBoxWriter : System.IO.TextWriter
    {
        private TextBoxBase control;
        private StringBuilder Builder;

        public TextBoxWriter(TextBoxBase control)
        {
            this.control = control;
            control.HandleCreated += new EventHandler(OnHandleCreated);
        }

        public override void Write(char ch)
        {
            Write(ch.ToString());
        }

        public override void Write(string s)
        {
            if ((control.IsHandleCreated))
            {
                AppendText(s);
            }
            else
            {
                BufferText(s);
            }
        }

        public override void WriteLine(string s)
        {
            // insert the current datetime
            Write(DateTime.Now + " " + s + Environment.NewLine);
        }
        
        private void BufferText(string s)
        {
            if ((Builder == null))
                {
                Builder = new StringBuilder();
                }
            Builder.Append(s);
        }

        private void AppendText(string s)
        {
            if ((Builder == null == false))
            {
                control.AppendText(Builder.ToString());
                Builder = null;
            }
            control.AppendText(s);
        }

        private void OnHandleCreated(object sender, EventArgs e)
        {
            if ((Builder == null == false))
            {
                control.AppendText(Builder.ToString());
                Builder = null;
            }
        }
        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }
    }
}
